package com.ruoyi.backend2.utils;

import java.util.HashMap;
import java.util.Map;

public class GlobalThreadLocalUtil {

    private static final Map<String, ThreadLocal<Object>> threadLocals = new HashMap<>();

    public static <T> void set(String key, T value) {
        ThreadLocal<T> threadLocal = getOrCreateThreadLocal(key);
        threadLocal.set(value);
    }

    public static <T> T get(String key) {
        ThreadLocal<T> threadLocal = (ThreadLocal<T>) threadLocals.get(key);
        if (threadLocal!= null) {
            return threadLocal.get();
        }
        return null;
    }

    private static <T> ThreadLocal<T> getOrCreateThreadLocal(String key) {
        ThreadLocal<T> threadLocal = (ThreadLocal<T>) threadLocals.get(key);
        if (threadLocal == null) {
            threadLocal = new ThreadLocal<>();
            threadLocals.put(key, (ThreadLocal<Object>) threadLocal);
        }
        return threadLocal;
    }
}